package com.it.gmall.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class DeadLetterMqConfig {

    // 需要用到的常量
    // 交换机
    public static final String exchange_dead = "exchange.dead";
    // 死信routing key
    public static final String routing_dead_1 = "routing.dead.1";
    // routing key
    public static final String routing_dead_2 = "routing.dead.2";
    // 死信队列
    public static final String queue_dead_1 = "queue.dead.1";
    // 普通队列
    public static final String queue_dead_2 = "queue.dead.2";

    // 交换机(死信交换机)
    @Bean
    public Exchange deadLetterExchange(){
        return ExchangeBuilder.directExchange(exchange_dead).build();
    }

    // 死信队列
    @Bean
    public Queue deadQueue(){
        Map<String, Object> arguments = new HashMap<>();

        // 延迟时间 以毫秒为单位
        arguments.put("x-message-ttl",10*1000);
        // 死信交换机 过期转发的交换机
        arguments.put("x-dead-letter-exchange",exchange_dead);
        // 死信routing key 过期换发的routingkey
        arguments.put("x-dead-letter-routing-key",routing_dead_2);

        return QueueBuilder.durable(queue_dead_1).withArguments(arguments).build();
    }

    // 普通队列
    @Bean
    public Queue normalQueue(){
        return QueueBuilder.durable(queue_dead_2).build();
    }

    // 绑定死信交换机和死信队列
    @Bean
    public Binding bindingDeadLetterExchangeAndQueue(
            @Qualifier("deadQueue") Queue deadQueue,
            @Qualifier("deadLetterExchange") Exchange deadLetterExchange
    ){
        return BindingBuilder.bind(deadQueue).to(deadLetterExchange).with(routing_dead_1).noargs();
    }

    // 绑定普通交换机和普通队列
    @Bean
    public Binding bindingExchangeAndQueue(
            @Qualifier("normalQueue") Queue normalQueue,
            @Qualifier("deadLetterExchange") Exchange deadLetterExchange
    ){
        return BindingBuilder.bind(normalQueue).to(deadLetterExchange).with(routing_dead_2).noargs();
    }
}
